package com.music.lrc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.music.mp3.Lrc;

public class LrcProcessor {
	//歌词对象
	Lrc l=null;
	//歌词对应毫秒值
	Long lrcTime=null;
	//对应显示的歌词
	String content=null;
    //用户保存所有的歌词和时间点信息间的映射关系的Map
    private LinkedHashMap<Long, String> maps = new LinkedHashMap<Long, String>();
    public  Lrc process(InputStream in){
    	InputStreamReader re=new InputStreamReader(in);
    	BufferedReader reader=new BufferedReader(re);
    	String temp=null;
    	l=new Lrc();
    	try {
			while((temp=reader.readLine())!=null){
				  setLrc(temp);
			}
			l.setContent(maps);
		} catch (IOException e) {
			return null;
		}
    	return l;
    }
    public void setLrc(String str){
    	if (str.startsWith("[ti:")) {
		    String title = str.substring(1, str.length() - 1); 
		    //System.out.println("title--->" + title); 
		   l.setTitle(title);
		 
		}
		// 取得歌手信息   
		else if (str.startsWith("[ar:")) {   
		     String singer = str.substring(1, str.length() - 1);   
		     //System.out.println("singer--->" + singer);   
		     l.setSinger(singer);   
		 
		}
		// 取得专辑信息  
		else if (str.startsWith("[al:")) {
		     String album = str.substring(1, str.length() - 1);   
		 //    System.out.println("album--->" + album);   
		     l.setAlbum(album); 
		  
		}
		else if (str.startsWith("[by:")) {
		     String lrcEditer = str.substring(1, str.length() - 1);   
		   //  System.out.println("album--->" + album);   
		     l.setLrcEditer(lrcEditer); 
		}else{
			// 设置正则规则   
			String reg = "\\[(\\d{2}:\\d{2}\\.\\d{2})\\]";
			// 编译   
			Pattern pattern = Pattern.compile(reg);
			Matcher matcher = pattern.matcher(str);
			if(matcher.find()){
				String msg=matcher.group();
				
				String timeStr=msg.substring(1, msg.length()-1);
				
				lrcTime=parseTime(timeStr);
				
				String[] s=str.split("\\]");
				if(s.length>=2){
					content=s[1];
				
					maps.put(lrcTime, content);
				}
				
			}
		}
    }
    public Long parseTime(String timeStr){
		String s[]=timeStr.split(":");
		int min=Integer.parseInt(s[0]);
	    String ss[]=s[1].split("\\.");
	    int sec=Integer.parseInt(ss[0]);
	    int mil=Integer.parseInt(ss[1]);
	    return min*60*1000+sec*1000+mil*10L;//此处的L就相当于把int转换为Long
	}
}
